<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>到底什么是线程安全和线程不安全？ | Finen&#39;s Blog</title>
    <meta name="generator" content="VuePress 1.4.1">
    <link rel="icon" href="/logo.png">
    <link rel="manifest" href="/manifest.json">
    <link rel="apple-touch-icon" href="/icons/apple-touch-icon-152x152.png">
    <link rel="mask-icon" href="/icons/safari-pinned-tab.svg" color="#3eaf7c">
    <meta name="description" content="Stay Hungry! Stay Foolish!">
    <meta name="theme-color" content="#3eaf7c">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="msapplication-TileImage" content="/icons/msapplication-icon-144x144.png">
    <meta name="msapplication-TileColor" content="#000000">
    <link rel="preload" href="/assets/css/0.styles.331bc503.css" as="style"><link rel="preload" href="/assets/js/app.8657dc36.js" as="script"><link rel="preload" href="/assets/js/3.655fda8f.js" as="script"><link rel="preload" href="/assets/js/25.0a52df22.js" as="script"><link rel="preload" href="/assets/js/11.32858d9c.js" as="script"><link rel="prefetch" href="/assets/js/1.af5e15a9.js"><link rel="prefetch" href="/assets/js/10.3d57a2e0.js"><link rel="prefetch" href="/assets/js/12.cef9d203.js"><link rel="prefetch" href="/assets/js/13.02beb1f0.js"><link rel="prefetch" href="/assets/js/14.7efc03c9.js"><link rel="prefetch" href="/assets/js/15.6bbbab3f.js"><link rel="prefetch" href="/assets/js/16.f90edb71.js"><link rel="prefetch" href="/assets/js/17.0d4d6c13.js"><link rel="prefetch" href="/assets/js/18.76dd8979.js"><link rel="prefetch" href="/assets/js/19.7da82e6f.js"><link rel="prefetch" href="/assets/js/20.55ee1642.js"><link rel="prefetch" href="/assets/js/21.088a02d1.js"><link rel="prefetch" href="/assets/js/22.73d5a697.js"><link rel="prefetch" href="/assets/js/23.829e24c3.js"><link rel="prefetch" href="/assets/js/24.2f258433.js"><link rel="prefetch" href="/assets/js/26.1c66cc2f.js"><link rel="prefetch" href="/assets/js/27.aa781144.js"><link rel="prefetch" href="/assets/js/28.b2cf7947.js"><link rel="prefetch" href="/assets/js/29.b61b1598.js"><link rel="prefetch" href="/assets/js/30.ba0ae8b1.js"><link rel="prefetch" href="/assets/js/31.7637d043.js"><link rel="prefetch" href="/assets/js/32.e552a016.js"><link rel="prefetch" href="/assets/js/33.334376b0.js"><link rel="prefetch" href="/assets/js/34.08c95f99.js"><link rel="prefetch" href="/assets/js/35.76b6b95d.js"><link rel="prefetch" href="/assets/js/36.539b6d80.js"><link rel="prefetch" href="/assets/js/37.850783a5.js"><link rel="prefetch" href="/assets/js/38.06c33708.js"><link rel="prefetch" href="/assets/js/39.85fc61d5.js"><link rel="prefetch" href="/assets/js/4.12c21fd1.js"><link rel="prefetch" href="/assets/js/40.cdc93796.js"><link rel="prefetch" href="/assets/js/41.be79357e.js"><link rel="prefetch" href="/assets/js/42.e1ea76e5.js"><link rel="prefetch" href="/assets/js/43.06bf748b.js"><link rel="prefetch" href="/assets/js/44.ebd514b5.js"><link rel="prefetch" href="/assets/js/45.12908515.js"><link rel="prefetch" href="/assets/js/46.78fb0130.js"><link rel="prefetch" href="/assets/js/47.1a3b6cfd.js"><link rel="prefetch" href="/assets/js/48.ef04cdb5.js"><link rel="prefetch" href="/assets/js/49.763fd944.js"><link rel="prefetch" href="/assets/js/5.e50a6b6f.js"><link rel="prefetch" href="/assets/js/50.c8a7a24d.js"><link rel="prefetch" href="/assets/js/51.aaa9e6c7.js"><link rel="prefetch" href="/assets/js/52.7d3a85df.js"><link rel="prefetch" href="/assets/js/53.00784a7d.js"><link rel="prefetch" href="/assets/js/54.bd3845dd.js"><link rel="prefetch" href="/assets/js/55.10a67e4b.js"><link rel="prefetch" href="/assets/js/56.eb909b5a.js"><link rel="prefetch" href="/assets/js/57.4b821666.js"><link rel="prefetch" href="/assets/js/58.1db8af1f.js"><link rel="prefetch" href="/assets/js/59.d3045373.js"><link rel="prefetch" href="/assets/js/6.f25d4964.js"><link rel="prefetch" href="/assets/js/60.e1ccc619.js"><link rel="prefetch" href="/assets/js/61.eca4de24.js"><link rel="prefetch" href="/assets/js/62.be7238a5.js"><link rel="prefetch" href="/assets/js/63.a6ace044.js"><link rel="prefetch" href="/assets/js/64.bbd88e61.js"><link rel="prefetch" href="/assets/js/65.1f6c1848.js"><link rel="prefetch" href="/assets/js/66.d22e96e8.js"><link rel="prefetch" href="/assets/js/67.80ad6427.js"><link rel="prefetch" href="/assets/js/68.130aa1f6.js"><link rel="prefetch" href="/assets/js/69.4b778299.js"><link rel="prefetch" href="/assets/js/7.9c54e368.js"><link rel="prefetch" href="/assets/js/70.edcac904.js"><link rel="prefetch" href="/assets/js/71.90aa842c.js"><link rel="prefetch" href="/assets/js/72.4cb8aeae.js"><link rel="prefetch" href="/assets/js/73.6f272f7b.js"><link rel="prefetch" href="/assets/js/74.d36a7a16.js"><link rel="prefetch" href="/assets/js/75.362400fa.js"><link rel="prefetch" href="/assets/js/76.140673a6.js"><link rel="prefetch" href="/assets/js/77.5f1336bf.js"><link rel="prefetch" href="/assets/js/78.6105e050.js"><link rel="prefetch" href="/assets/js/79.dd680c04.js"><link rel="prefetch" href="/assets/js/8.786d8198.js"><link rel="prefetch" href="/assets/js/80.ebfb944f.js"><link rel="prefetch" href="/assets/js/81.892d344c.js"><link rel="prefetch" href="/assets/js/9.b0b77105.js">
    <link rel="stylesheet" href="/assets/css/0.styles.331bc503.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">Finen's Blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/post/" class="nav-link">
  文章
</a></div><div class="nav-item"><a href="/archives/" class="nav-link">
  归档
</a></div><div class="nav-item"><a href="/tags/" class="nav-link">
  标签云
</a></div><div class="nav-item"><a href="/friends/" class="nav-link">
  友人帐
</a></div> <a href="https://github.com/hirCodd" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/post/" class="nav-link">
  文章
</a></div><div class="nav-item"><a href="/archives/" class="nav-link">
  归档
</a></div><div class="nav-item"><a href="/tags/" class="nav-link">
  标签云
</a></div><div class="nav-item"><a href="/friends/" class="nav-link">
  友人帐
</a></div> <a href="https://github.com/hirCodd" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav>  <!----> </aside> <main class="page"> <div class="title-content"><div class="el-card box-cards is-never-shadow"><!----><div class="el-card__body"><h2>到底什么是线程安全和线程不安全？</h2> <div class="page-info"><i aria-hidden="true" class="el-icon-s-custom"></i> <span class="i-text">Finen</span> <i aria-hidden="true" class="el-icon-collection-tag"><span class="i-text">Java</span></i> <i aria-hidden="true" class="el-icon-time"></i> <span class="i-text">2021-03-26</span> <span id="/blog/java/java/%E5%88%B0%E5%BA%95%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E5%92%8C%E7%BA%BF%E7%A8%8B%E4%B8%8D%E5%AE%89%E5%85%A8.html" data-flag-title="到底什么是线程安全和线程不安全？" class="leancloud-visitors"><i aria-hidden="true" class="el-icon-view"></i> <i class="leancloud-visitors-count">1000000</i></span></div></div></div></div> <div class="theme-default-content content__default"><h2 id="_1-什么是线程安全？"><a href="#_1-什么是线程安全？" class="header-anchor">#</a> 1.什么是线程安全？</h2> <p>维基百科给出的定义如下：</p> <blockquote><p>线程安全是程式设计中的术语，指<strong>某个函数、函数库</strong>在<strong>多线程环境</strong>中被调用时，能够正确地处理多个线程之间的<strong>共享变量</strong>，使程序功能正确完成。</p></blockquote> <p>在《Java并发编程实战》一书中给出如下定义：</p> <blockquote><p>一个对象是否需要是线程安全的，取决于它是否被多个线程访问。<strong>这只和对象在程序中是以何种方式被使用的有关，和对象本身具体是做什么的无关。</strong></p></blockquote> <p>在《深入Java虚拟机》一书中给出如下定义：</p> <blockquote><p>当多个线程访问同一个对象时，**如果不用考虑这些线程在运行时环境下的调度和交替运行，也不需要进行额外的同步，或者在调用方进行任何其他的协调操作，**调用这个对象的行为都可以获取正确的结果，那这个对象是线程安全的。</p></blockquote> <p>线程安全：在多线程同时访问一个资源时，线程间依照某种方式访问资源时，访问的结果总是能获取到正确的结果。</p> <h2 id="_2-java内存模型-jmm"><a href="#_2-java内存模型-jmm" class="header-anchor">#</a> 2.Java内存模型-JMM</h2> <p><img src="https://gitee.com/forge-logic/images-lib/raw/master/img/16bf62d8c174d776.jpg" alt="16bf62d8c174d776"></p> <p>上图描述了一个多线程执行场景。 线程 A 和线程 B 分别对主内存的<code>变量</code>进行读写操作。其中<strong>主内存</strong>中的<code>变量</code>为<code>共享变量</code>,也就是说此变量只此一份，多个线程间共享。但是线程不能直接读写主内存的<code>共享变量</code>，每个线程都有自己的<strong>工作内存</strong>，线程需要读写主内存的<code>共享变量</code>时需要先将该变量拷贝一份副本到自己的工作内存，然后在自己的工作内存中对该变量进行所有操作，线程工作内存对变量副本完成操作之后需要将结果同步至主内存。</p> <blockquote><p>线程的工作内存是线程私有内存，线程间无法互相访问对方的工作内存。</p></blockquote> <h2 id="_3-共享变量-共享资源"><a href="#_3-共享变量-共享资源" class="header-anchor">#</a> 3.共享变量(共享资源)</h2> <p>所谓共享变量，指的是多个线程都可以操作的变量。进程是分配资源的基本单位，线程是执行的基本单位。所以，多个线程之间是可以共享一部分进程中的数据的。在JVM中，Java堆和方法区的区域是多个线程共享的数据区域。也就是说，多个线程可以操作保存在堆或者方法区中的同一个数据。那么，<strong>保存在堆和方法区中的变量就是Java中的共享变量。</strong></p> <p>那么，Java中哪些变量是存放在堆中，哪些变量是存放在方法区中，又有哪些变量是存放在栈中的呢？</p> <p>Java中共有三种变量，<strong>分别是类变量、成员变量和局部变量。他们分别存放在JVM的方法区、堆内存和栈内存中。</strong>（栈内存是程序线程独占空间）</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Variables</span> <span class="token punctuation">{</span>

    <span class="token comment">/**
     * 类变量
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">int</span> a<span class="token punctuation">;</span>

    <span class="token comment">/**
     * 成员变量
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> b<span class="token punctuation">;</span>

    <span class="token comment">/**
     * 局部变量
     * @param c
     */</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token keyword">int</span> c<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">int</span> d<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br></div></div><p>上面定义的三个变量中，变量a就是类变量，变量b就是成员变量，而变量c和d是局部变量。</p> <p>所以，变量a和b是共享变量，变量c和d是非共享变量。所以如果遇到多线程场景，对于变量a和b的操作是需要考虑线程安全的，而对于线程c和d的操作是不需要考虑线程安全的。</p> <h2 id="_4-线程安全的实现"><a href="#_4-线程安全的实现" class="header-anchor">#</a> 4.线程安全的实现</h2> <h3 id="_4-1-无状态实现"><a href="#_4-1-无状态实现" class="header-anchor">#</a> 4.1 无状态实现</h3> <p>在大多数情况下，多线程应用中的错误是错误地在多个线程之间共享状态的结果。</p> <p>因此，我们要研究的第一种方法是 <strong>使用无状态实现</strong>来实现线程安全。</p> <p>为了更好地理解这种方法，让我们考虑一个带有静态方法的简单工具类，该方法可以计算数字的阶乘：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MathUtils</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">BigInteger</span> <span class="token function">factorial</span><span class="token punctuation">(</span><span class="token keyword">int</span> number<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">BigInteger</span> f <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">BigInteger</span><span class="token punctuation">(</span><span class="token string">&quot;1&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">2</span><span class="token punctuation">;</span> i <span class="token operator">&lt;=</span> number<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            f <span class="token operator">=</span> f<span class="token punctuation">.</span><span class="token function">multiply</span><span class="token punctuation">(</span><span class="token class-name">BigInteger</span><span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> f<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p><strong><code>factorial</code>方法是一种无状态确定性函数。</strong> 确定性是指：给定特定的输入，它将始终产生相同的输出。</p> <p>该方法<strong>既不依赖外部状态，也不维护自身的状态</strong>。因此，它被认为是线程安全的，并且可以同时被多个线程安全地调用。</p> <p>所有线程都可以安全地调用 <code>factorial</code> 方法，并且将获得预期结果，而不会互相干扰，也不会更改该方法为其他线程生成的输出。</p> <p>因此，<strong>无状态实现是实现线程安全的最简单方法</strong>。</p> <h3 id="_4-2-不可变的实现"><a href="#_4-2-不可变的实现" class="header-anchor">#</a> 4.2  不可变的实现</h3> <p><strong>如果我们需要在不同线程之间共享状态，则可以通过使它们成为不可变对象来创建线程安全类</strong>。</p> <p>不变性是一个功能强大，与语言无关的概念，在Java中相当容易实现。</p> <p><strong>当类实例的内部状态在构造之后无法修改时，它是不可变的</strong>。</p> <p>在Java中创建不可变类的最简单方法是声明所有字段为 <em>private</em> 和 <em>final</em> ，且不提供 setter：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MessageService</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">String</span> message<span class="token punctuation">;</span>
 
    <span class="token keyword">public</span> <span class="token class-name">MessageService</span><span class="token punctuation">(</span><span class="token class-name">String</span> message<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>message <span class="token operator">=</span> message<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token comment">// 标准 getter</span>
    
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>一个 <em>MessageService</em> 对象实际上是不可变的，因为它的状态在构造之后不能更改。因此，它是线程安全的。</p> <p>此外，如果 <em>MessageService</em> 实际上是<strong>可变</strong>的，但是多个线程仅对其具有<strong>只读</strong>访问权限，那么它也是线程安全的。</p> <p>因此，<strong>不变性是实现线程安全的另一种方法</strong>。</p> <h3 id="_4-3-线程私有-threadlocal-字段"><a href="#_4-3-线程私有-threadlocal-字段" class="header-anchor">#</a> 4.3 线程私有 (ThreadLocal) 字段</h3> <p>在面向对象编程（OOP）中，对象实际上需要通过字段维护状态并通过一种或多种方法来实现行为。</p> <p>如果我们确实需要维护状态，<strong>则可以通过使它们的字段成为线程局部的来创建不在线程之间共享状态的线程安全类。</strong></p> <p>通过简单地在 <em><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html" target="_blank" rel="noopener noreferrer">Thread<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></em> 类中定义私有字段，我们可以轻松创建其字段为线程局部的类。</p> <p>例如，我们可以定义一个存储整数数组的 <em>Thread</em> 类：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadA</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> numbers <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        numbers<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p>而另一个类可能拥有一个字符串数组：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadB</span> <span class="token keyword">extends</span> <span class="token class-name">Thread</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">String</span><span class="token punctuation">&gt;</span></span> letters <span class="token operator">=</span> <span class="token class-name">Arrays</span><span class="token punctuation">.</span><span class="token function">asList</span><span class="token punctuation">(</span><span class="token string">&quot;a&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;b&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;c&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;d&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;e&quot;</span><span class="token punctuation">,</span> <span class="token string">&quot;f&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        letters<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token operator">::</span><span class="token function">println</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p><strong>在这两种实现中，这些类都有其自己的状态，但是不与其他线程共享。因此，这些类是线程安全的。</strong></p> <p>同样，我们可以通过将 <em><a href="https://www.baeldung.com/java-threadlocal" target="_blank" rel="noopener noreferrer">ThreadLocal<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></em> 实例分配给一个字段来创建线程私有字段。</p> <p>例如，让我们考虑以下 <em>StateHolder</em> 类：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">StateHolder</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">String</span> state<span class="token punctuation">;</span>
 
    <span class="token comment">// 标准的构造函数和 getter</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br></div></div><p>我们可以很容易地使其成为线程局部（ThreadLocal）变量，如下所示：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadState</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">StateHolder</span><span class="token punctuation">&gt;</span></span> statePerThread <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadLocal</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">StateHolder</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        
        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">protected</span> <span class="token class-name">StateHolder</span> <span class="token function">initialValue</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StateHolder</span><span class="token punctuation">(</span><span class="token string">&quot;active&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">;</span>
 
    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token class-name">StateHolder</span> <span class="token function">getState</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> statePerThread<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br></div></div><p>线程局部字段与普通类字段非常相似，不同之处在于，每个通过setter / getter访问它们的线程都将获得该字段的独立初始化副本，以便每个线程都有自己的状态。</p> <h3 id="_4-4-同步集合类"><a href="#_4-4-同步集合类" class="header-anchor">#</a> 4.4 同步集合类</h3> <p>通过使用<a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html" target="_blank" rel="noopener noreferrer">collections框架<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> 中包含的一组同步包装器，我们可以轻松地创建线程安全的<a href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html" target="_blank" rel="noopener noreferrer">collections<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>。</p> <p>例如，我们可以使用以下<a href="https://www.baeldung.com/java-synchronized-collections" target="_blank" rel="noopener noreferrer">同步包装之一<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>来创建线程安全的集合：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>Collection&lt;Integer&gt; syncCollection = Collections.synchronizedCollection(new ArrayList&lt;&gt;());
Thread thread1 = new Thread(() -&gt; syncCollection.addAll(Arrays.asList(1, 2, 3, 4, 5, 6)));
Thread thread2 = new Thread(() -&gt; syncCollection.addAll(Arrays.asList(7, 8, 9, 10, 11, 12)));
thread1.start();
thread2.start();
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><p>让我们记住，同步集合在每种方法中都使用内在锁定（我们将在后面介绍内在锁定）。</p> <p>这意味着<strong>该方法一次只能由一个线程访问，而其他线程将被阻塞，直到该方法被第一个线程解锁。</strong></p> <p>因此，由于同步访问的基本逻辑，同步会对性能造成不利影响。</p> <h3 id="_4-5-支持并发的集合"><a href="#_4-5-支持并发的集合" class="header-anchor">#</a> 4.5 支持并发的集合</h3> <p>除了同步集合，我们可以使用并发集合来创建线程安全的集合。</p> <p>Java提供了 <em><a href="https://docs.oracle.com/javase/8/docs/api/?java/util/concurrent/package-summary.html" target="_blank" rel="noopener noreferrer">java.util.concurrent<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></em> 包，其中包含多个并发集合，例如 <em><a href="https://docs.oracle.com/javase/8/docs/api/?java/util/concurrent/package-summary.html" target="_blank" rel="noopener noreferrer">ConcurrentHashMap<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></em> ：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>Map&lt;String,String&gt; concurrentMap = new ConcurrentHashMap&lt;&gt;();
concurrentMap.put(&quot;1&quot;, &quot;one&quot;);
concurrentMap.put(&quot;2&quot;, &quot;two&quot;);
concurrentMap.put(&quot;3&quot;, &quot;three&quot;);
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p>与同步对象不同，<strong>并发集合通过将其数据划分为段来实现线程安全</strong>。例如，在 <em>ConcurrentHashMap</em> 中，多个线程可以获取不同 Map 段上的锁，因此多个线程可以同时访问 <em>Map</em> 。</p> <p>由于并发线程访问的先天优势，<strong>并发集合类</strong>具备<strong>远超同步集合类更好的性能</strong>。</p> <p>值得一提的是，<strong>同步集合和并发集合仅使集合本身具有线程安全性，而不使content变得线程安全</strong>。</p> <h3 id="_4-6-原子化对象"><a href="#_4-6-原子化对象" class="header-anchor">#</a> 4.6 原子化对象</h3> <p>使用Java提供的一组<a href="https://www.baeldung.com/java-atomic-variables" target="_blank" rel="noopener noreferrer">原子类<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>（包括 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html" target="_blank" rel="noopener noreferrer">AtomicInteger<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>，<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html" target="_blank" rel="noopener noreferrer">AtomicLong<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>，<a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicBoolean.html" target="_blank" rel="noopener noreferrer">AtomicBoolean<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> 和 <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicReference.html" target="_blank" rel="noopener noreferrer">AtomicReference<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> )也可以实现线程安全。</p> <p><strong>原子类使我们能够执行安全的原子操作，而无需使用同步</strong>。原子操作在单个机器级别的操作中执行。</p> <p>要了解解决的问题，让我们看下面的 <em>Counter</em> 类：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Counter</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">int</span> counter <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
    
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">incrementCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        counter <span class="token operator">+=</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> counter<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p><strong>让我们假设在竞争条件下，两个线程同时访问 <code>increasingCounter()</code> 方法。</strong></p> <p>从理论上讲， <em>counter</em> 字段的最终值为2。但是我们不确定结果如何，因为线程在同一时间执行同一代码块，并且增量不是原子的。</p> <p>让我们使用 <em>AtomicInteger</em> 对象创建 <em>Counter</em> 类的线程安全实现：</p> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AtomicCounter</span> <span class="token punctuation">{</span>
    
    <span class="token keyword">private</span> <span class="token keyword">final</span> <span class="token class-name">AtomicInteger</span> counter <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">AtomicInteger</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">incrementCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        counter<span class="token punctuation">.</span><span class="token function">incrementAndGet</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    
    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getCounter</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> counter<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p><strong>这是线程安全的，因为在++增量执行多个操作的同时， <code>增量和获取</code> 是原子的</strong>。</p> <h3 id="_4-7-同步方法"><a href="#_4-7-同步方法" class="header-anchor">#</a> 4.7 同步方法</h3> <p>尽管较早的方法对于集合和基元非常有用，但有时我们需要的控制权要强于此。</p> <p>因此，可用于实现线程安全的另一种常见方法是实现同步方法。</p> <p>简而言之，<strong>一次只能有一个线程可以访问同步方法，同时阻止其他线程对该方法的访问</strong>。其他线程将保持阻塞状态，直到第一个线程完成或该方法引发异常。</p> <p>我们可以通过使它成为同步方法，以另一种方式创建线程安全版本的 <em>creationCounter()</em> ：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public synchronized void incrementCounter() {
    counter += 1;
}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br></div></div><p>我们通过与前缀的方法签名创建一个同步方法 synchronized 关键字。</p> <p>由于一次一个线程可以访问一个同步方法，因此一个线程将执行 <em>crementCounter()</em> 方法，而其他线程将执行相同的操作。任何重叠的执行都不会发生。</p> <p><strong>同步方法依赖于“内部锁”或“监视器锁”的使用</strong>。固有锁是与特定类实例关联的隐式内部实体。</p> <p>在多线程上下文中，术语 <em>monitor</em> 是指对关联对象执行锁的角色，因为它强制对一组指定的方法或语句进行排他访问。</p> <p><strong>当线程调用同步方法时，它将获取内部锁</strong>。线程完成执行方法后，它将释放锁，从而允许其他线程获取锁并获得对方法的访问。</p> <p>我们可以在实例方法，静态方法和语句（已同步的语句）中实现同步。</p> <h3 id="_4-8-同步语句"><a href="#_4-8-同步语句" class="header-anchor">#</a> 4.8  同步语句</h3> <p>有时，如果我们只需要使方法的一部分成为线程安全的，那么同步整个方法可能就显得过分了。</p> <p>为了说明这个用例，让我们重构 <em>increascountCounter</em> 方法：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public void incrementCounter() {
    // 此处可有额外不需同步的操作
    // ...
    synchronized(this) {
        counter += 1; 
    }
}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br></div></div><p>该示例很简单，但是它显示了如何创建同步语句。假设该方法现在执行了一些不需要同步的附加操作，我们仅通过将相关的状态修改部分包装在一个<strong>同步</strong>块中来对其进行<strong>同步</strong>。</p> <p>与同步方法不同，同步语句必须指定提供内部锁的对象，通常是<code>this</code>引用。</p> <p><strong>同步非常昂贵，因此使用此选项，我们尽可能只同步方法的相关部分</strong>。</p> <h3 id="_4-8-其他对象作为锁"><a href="#_4-8-其他对象作为锁" class="header-anchor">#</a> 4.8 其他对象作为锁</h3> <p>我们可以通过将另一个对象用作监视器锁定，来稍微改善 <em>Counter</em> 类 的线程安全实现。</p> <p>这不仅可以在多线程环境中提供对共享资源的协调访问，<strong>还可以使用外部实体来强制对资源进行独占访问</strong>：</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>public class ObjectLockCounter {
 
    private int counter = 0;
    private final Object lock = new Object();
    
    public void incrementCounter() {
        synchronized(lock) {
            counter += 1;
        }
    }
    
    // 标准 getter
}
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br></div></div><p>我们使用一个普通的 Object 实例来强制相互排斥。此实现稍好一些，因为它可以提高锁定级别的安全性。</p> <p>将 this 用于内部锁定时，<strong>攻击者可能会通过获取内部锁定并触发拒绝服务（DoS）条件来导致死锁。</strong></p> <p>相反，在使用其他对象时， <strong>无法从外部访问该私有实体</strong>。这使得攻击者更难获得锁定并导致死锁。</p> <h2 id="_5-参考文章"><a href="#_5-参考文章" class="header-anchor">#</a> 5.参考文章</h2> <p>1.什么是线程安全?.https://www.jianshu.com/p/44831d1d10d3</p> <p>2.深入理解Java并发编程（一）：到底什么是线程安全.https://www.hollischuang.com/archives/3060</p> <p>3.Java 并发基础——线程安全性.https://www.cnblogs.com/NeilZhang/p/8682266.html</p> <p>4.什么是线程安全以及如何实现？https://segmentfault.com/a/1190000023187634</p> <p>5.你真的知道什么是线程安全吗？.https://www.hoohack.me/2020/09/01/what-is-thread-safe</p> <p>6.(解释的比较清楚，透彻的)图解 Java 线程安全.https://juejin.cn/post/6844903890224152584</p> <p>7.Java进阶（二）当我们说线程安全时，到底在说什么.http://www.jasongj.com/java/thread_safe/</p></div> <footer class="page-edit"><!----> <!----></footer> <!---->  <div class="vcomment"><div id="vcomments"></div></div></main></div><div class="global-ui"><!----><!----></div></div>
    <script src="/assets/js/app.8657dc36.js" defer></script><script src="/assets/js/3.655fda8f.js" defer></script><script src="/assets/js/25.0a52df22.js" defer></script><script src="/assets/js/11.32858d9c.js" defer></script>
  </body>
</html>
